package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 响应对象
 * 该类的每个实例用于表示HTTP协议规定的一个响应内容
 * 每个响应都有三部分组成
 * 状态行，响应头，响应正文
 */
public class HttpServletResponse {
    private int statusCode = 200;//状态代码
    private String statusReason = "OK";//状态描述
    //响应头相关信息

    //响应正文相关信息
    private File contentFile;//响应正文对应的文件，该文件数据会作为正文内容发送

    private Socket socket;
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    public void response() throws IOException {
        //3.发送响应
        sendStatusLine();
        //3.1发送状态行
        sendHeaders();
        //3.2发送响应头
        sendContent();
        //3.3发送响应正文

        System.out.println("响应发送完毕");

    }
    //发送状态行
    private void sendStatusLine() throws IOException {
        String line = "HTTP/1.1"+" "+statusCode+" "+statusReason;
        println(line);
    }
    //发送响应头
    private void sendHeaders() throws IOException {
        println("Content-Type: text/html");
        println("Content-Length: "+contentFile.length());
        println("");//单独发送回车换行表示响应头发送完毕
    }
    //发送响应正文
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        try(
        FileInputStream fis = new FileInputStream(contentFile);
        ){
            byte[] data = new byte[1024*10];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
        }

    }


    private void println(String line) throws IOException {
        //通过
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//单独发送回车键
        out.write(10);//单独发送换行键
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }


}
